import re
class TextUtil:
    @staticmethod
    def has_chinese(text):
        """
        Detect whether Chinese Character included in text
        """
        pattern = re.compile("[\u4e00-\u9fa5]")
        result = pattern.search(text)
        return result is not None

    @staticmethod
    def replace_single_newline(text):
        """
        Due to latex/markdown do not treat single new line as real 'new line',
        remove it. 

        if a line is terminated with single '\n', it will be replace to space.
        Otherwise, the line break will be reserved. """
        new_text = ""
        i = 0
        while i < len(text):
            if text[i] == "\n":
                if (i == 0 or text[i-1] != "\n") and (i == len(text)-1 or text[i+1] != "\\"):
                    new_text += " "
                else:
                    new_text += "\n"
            else:
                new_text += text[i]
            i += 1
        return new_text

    @staticmethod
    def count_words(text):
        words = text.split()
        num_words = len(words)
        return num_words

    @staticmethod
    def add_percent_sign(text):
        """
        make the text as comments
        """
        lines = text.split("\n")
        new_lines = ["%" + line for line in lines]
        return "\n".join(new_lines)        
